/*
@author: ZZH
@date: 2021-11-05
@time: 14:17:38
@info: 单链表实现函数模板文件
*/
#pragma once
#include "SL-List-Base.h"
#include "operations.h"
#include "MemMana.h"
#include "stdio.h"

#define SLL_IMP_REF(type, siffix) typedef struct\
{\
    SLListNode_t node;\
    type value;\
}SLListNode_##siffix##_t, *pSLListNode_##siffix##_t;\
\
pSLList_t SLL_Create_##siffix();\
void SLL_CreateStatic_##siffix(pSLList_t list);\
uint8_t SLL_Insert_##siffix(pSLList_t list, type value);\
uint8_t SLL_Delete_##siffix(pSLList_t list, type value);\
type SLL_GetNodeValue_##siffix(pSLList_t list, uint32_t index);\
pSLListNode_t SLL_Search_##siffix(pSLList_t list, type value);

#define SLL_IMP_REF_PRINT(type, siffix) void SLL_Print_##siffix##_basic(pSLList_t list);

#define SLL_IMP_DEF(type, siffix) static SLL_CompareResult_t SLL_Compare_##siffix(pSLListNode_t node, void* value)\
{\
    type valueCmp = *(type*) value;\
    pSLListNode_##siffix##_t nodeCmp = container_of(node, SLListNode_##siffix##_t, node);\
\
    if (nodeCmp->value > valueCmp)\
        return SLL_Big;\
    else if (nodeCmp->value == valueCmp)\
        return SLL_Equal;\
    else\
        return SLL_Small;\
}\
\
static void SLL_Free_##siffix(pSLListNode_t node)\
{\
    Free(container_of(node, SLListNode_##siffix##_t, node));\
}\
\
pSLList_t SLL_Create_##siffix()\
{\
    pSLList_t list = __SLL_Create();\
    list->compare = SLL_Compare_##siffix;\
    list->free = SLL_Free_##siffix;\
    return list;\
}\
\
void SLL_CreateStatic_##siffix(pSLList_t list)\
{\
    __SLL_CreateStatic(list);\
\
    list->compare = SLL_Compare_##siffix;\
    list->free = SLL_Free_##siffix;\
}\
\
uint8_t SLL_Insert_##siffix(pSLList_t list, type value)\
{\
    pSLListNode_##siffix##_t newNode = Malloc(sizeof(SLListNode_##siffix##_t));\
    if (newNode == NULL)\
        return 0;\
\
    newNode->value = value;\
\
    return __SLL_Insert(list, &newNode->node);\
}\
\
uint8_t SLL_Delete_##siffix(pSLList_t list, type value)\
{\
    return __SLL_DeleteNode(list, SLL_Search(list, &value));\
}\
\
type SLL_GetNodeValue_##siffix(pSLList_t list, uint32_t index)\
{\
    pSLListNode_t node = __SLL_GetNode(list, index);\
    return container_of(node, SLListNode_##siffix##_t, node)->value;\
}\
pSLListNode_t SLL_Search_##siffix(pSLList_t list, type value)\
{\
    return SLL_Search(list, &value);\
}

#define SLL_IMP_DEF_PRINT(type, siffix, fmt) static void SLL_Visit_##siffix(pSLListNode_t node, uint32_t level)\
{\
    printf("[%d]: " fmt "\r\n", level, container_of(node, SLListNode_##siffix##_t, node)->value);\
}\
\
void SLL_Print_##siffix##_basic(pSLList_t list)\
{\
    __SLL_Visit visit_fn = list->visit;\
    list->visit = SLL_Visit_##siffix;\
    __SLL_Traverse(list);\
    list->visit = visit_fn;\
}
